package ${table.basePackage}.controller;

<#-- 获取主键字段类型 -->
<#assign pkType = "Long">
<#list columns as c>
  <#if (c.isPk?? && c.isPk) || (c.propertyName?? && c.propertyName?lower_case == "id")>
    <#if c.javaType?? && (c.javaType?contains("String") || c.javaType == "String")>
      <#assign pkType = "String">
    <#elseif c.javaType?? && c.javaType != "">
      <#assign pkType = c.javaType?split(".")?last>
    </#if>
    <#break>
  </#if>
</#list>

import java.io.IOException;
import java.util.List;
<#if table.templateType?has_content && table.templateType == 'multi'>
import java.util.Map;
</#if>

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.kexio.auth.annotation.RequiresPermission;
import com.kexio.common.dto.PageResponse;
import com.kexio.common.dto.Result;
import ${table.basePackage}.dto.${table.entityName}DTO;
import ${table.basePackage}.service.${table.entityName}Service;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * ${table.comment!table.entityName} - 接口控制器
 * 
 * 遵循Kexio开发规范：
 * - 使用@RequiresPermission注解进行权限控制
 * - 使用统一的Result响应格式
 * - 使用@Valid进行参数验证
 * - 异常统一由全局异常处理器捕获
 * - 使用DTO进行数据传输
 * - 支持Excel导入导出
 * - 租户隔离自动处理
 * 
 * @author ${user.name!"系统"}
 * @since ${now?string('yyyy-MM-dd HH:mm:ss')}
 */
@Tag(name = "${table.comment!table.entityName}管理")
@RestController
@RequestMapping("/${table.moduleName}/${lowerEntity}")
public class ${table.entityName}Controller {
    
    private static final Logger logger = LoggerFactory.getLogger(${table.entityName}Controller.class);

    @Autowired
    private ${table.entityName}Service ${lowerEntity}Service;

    /**
     * 分页查询${table.comment!table.entityName}
     *
     * @param queryDTO 查询条件（包含分页参数）
     * @return 分页结果
     */
    @Operation(summary = "分页查询${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:list")
    @GetMapping
    public Result<PageResponse<${table.entityName}DTO>> list(${table.entityName}DTO queryDTO) {
        PageResponse<${table.entityName}DTO> page = ${lowerEntity}Service.queryPage(queryDTO);
        return Result.success(page);
    }

    /**
     * 查询${table.comment!table.entityName}详情
     *
     * @param id 主键ID
     * @return ${table.comment!table.entityName}信息
     */
    @Operation(summary = "查询${table.comment!table.entityName}详情")
    @RequiresPermission("${permissionPrefix}:query")
    @GetMapping("/{id}")
    public Result<${table.entityName}DTO> get(@PathVariable ${pkType} id) {
        ${table.entityName}DTO dto = ${lowerEntity}Service.getDetail(id);
        return Result.success(dto);
    }

    /**
     * 新增${table.comment!table.entityName}
     *
     * @param dto ${table.comment!table.entityName}信息
     * @return 操作结果
     */
    @Operation(summary = "新增${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:add")
    @PostMapping
    public Result<${table.entityName}DTO> add(@Valid @RequestBody ${table.entityName}DTO dto) {
        ${table.entityName}DTO result = ${lowerEntity}Service.create(dto);
        return Result.success("创建成功", result);
    }

<#if table.templateType?has_content && table.templateType == 'multi'>
    /**
     * 新增${table.comment!table.entityName}及关联数据
     *
     * @param dto ${table.comment!table.entityName}信息（含关联数据）
     * @return 操作结果
     */
    @Operation(summary = "新增${table.comment!table.entityName}及关联数据")
    @RequiresPermission("${permissionPrefix}:add")
    @PostMapping("/with-relations")
    public Result<${table.entityName}DTO> addWithRelations(@Valid @RequestBody ${table.entityName}DTO dto) {
        ${table.entityName}DTO result = ${lowerEntity}Service.createWithRelations(dto);
        return Result.success("创建成功", result);
    }

</#if>
    /**
     * 修改${table.comment!table.entityName}
     *
     * @param id 主键ID
     * @param dto ${table.comment!table.entityName}信息
     * @return 操作结果
     */
    @Operation(summary = "修改${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:edit")
    @PutMapping("/{id}")
    public Result<${table.entityName}DTO> update(@PathVariable ${pkType} id, @Valid @RequestBody ${table.entityName}DTO dto) {
        ${table.entityName}DTO result = ${lowerEntity}Service.update(id, dto);
        return Result.success("更新成功", result);
    }

<#if table.templateType?has_content && table.templateType == 'multi'>
    /**
     * 修改${table.comment!table.entityName}及关联数据
     *
     * @param id 主键ID
     * @param dto ${table.comment!table.entityName}信息（含关联数据）
     * @return 操作结果
     */
    @Operation(summary = "修改${table.comment!table.entityName}及关联数据")
    @RequiresPermission("${permissionPrefix}:edit")
    @PutMapping("/{id}/with-relations")
    public Result<${table.entityName}DTO> updateWithRelations(@PathVariable ${pkType} id, @Valid @RequestBody ${table.entityName}DTO dto) {
        ${table.entityName}DTO result = ${lowerEntity}Service.updateWithRelations(id, dto);
        return Result.success("更新成功", result);
    }

</#if>
    /**
     * 删除${table.comment!table.entityName}
     *
     * @param id 主键ID
     * @return 操作结果
     */
    @Operation(summary = "删除${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:remove")
    @DeleteMapping("/{id}")
    public Result<Void> remove(@PathVariable ${pkType} id) {
        ${lowerEntity}Service.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 批量删除${table.comment!table.entityName}
     *
     * @param ids 主键ID列表
     * @return 操作结果
     */
    @Operation(summary = "批量删除${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:remove")
    @DeleteMapping("/batch")
    public Result<Void> batchDelete(@RequestBody List<${pkType}> ids) {
        ${lowerEntity}Service.deleteBatch(ids);
        return Result.success("批量删除成功");
    }

    /**
     * 导出${table.comment!table.entityName}
     *
     * @param queryDTO 查询条件
     * @param response HTTP响应
     */
    @Operation(summary = "导出${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:export")
    @GetMapping("/export")
    public void export(${table.entityName}DTO queryDTO, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=${table.comment!table.entityName}.xlsx");
        
        ${lowerEntity}Service.exportData(queryDTO, response.getOutputStream());
    }

    /**
     * 下载导入模板
     *
     * @param response HTTP响应
     */
    @Operation(summary = "下载导入模板")
    @RequiresPermission("${permissionPrefix}:import")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=${table.comment!table.entityName}导入模板.xlsx");
        
        ${lowerEntity}Service.downloadImportTemplate(response.getOutputStream());
    }

    /**
     * 导入${table.comment!table.entityName}
     *
     * @param file Excel文件
     * @param updateSupport 是否更新已存在的数据
     * @return 导入结果
     */
    @Operation(summary = "导入${table.comment!table.entityName}")
    @RequiresPermission("${permissionPrefix}:import")
    @PostMapping("/import")
    public Result<Map<String, Object>> importData(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws IOException {
        
        Map<String, Object> result = ${lowerEntity}Service.importData(file.getInputStream(), updateSupport);
        return Result.success(result);
    }
}
